<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <audio-file-search @search="reload" />
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :scroll="{ x: 800 }"
        cache-key="proSystemFileTable"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'path'">
            <a :href="record.url" target="_blank">
              {{ record.path }}
            </a>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="openPlay(record)">播放</a>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 播放弹窗 -->
    <audio-play
      :recordList="currentRecordList"
      v-model:visible="showPlay"
      @done="reload"
    />
  </div>
</template>

<script setup>
import { computed, createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import {
    UploadOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import { messageLoading, toDateString } from 'ele-admin-pro/es';
  import AudioFileSearch from './audio-file-search.vue';
  import AudioPlay from './audio-play.vue';
  import {
    pageFiles,
    removeFile,
    removeFiles,
    uploadFile
  } from '@/api/system/file';
  import { defineProps } from '@vue/runtime-core';

  const props = defineProps({
    // 机构 id
    groupId: Number,
    // 全部机构
    groupList: Array,
    // 当前所属组织
    currentGroupName: String,
    // 当前对讲组号码
    currentGroupNo: String
  });
  // 表格实例
  const tableRef = ref(null);

  // 是否显示播放弹窗
  const showPlay = ref(false);

  // 当前播放数据
  const current = ref(null);

  // 当前行的 录音文件列表
  const currentRecordList = ref([]);

  // 表格列配置
  const columns = ref([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '主叫',
      dataIndex: 'callingNo',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true
    },
    {
      title: '被叫',
      dataIndex: 'calledNo',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true
    },
    {
      title: '对讲组',
      dataIndex: 'calledGroupNo',
      sorter: true,
      showSorterTooltip: false,
      customRender: ({ text  }) => {
        // const key = String(calledGroupNo);
        console.log('calledGroupNo===customRender===>',text,groupMap.value?.[text]);
        return groupMap.value?.[text] ?? text;
      },
      ellipsis: true
    },
    {
      title: '录音开始时间',
      dataIndex: 'beginTime',
      sorter: true,
      showSorterTooltip: false,
      customRender: ({ text }) => toDateString(text),
      ellipsis: true
    },
    {
      title: '录音结束时间',
      dataIndex: 'endTime',
      sorter: true,
      showSorterTooltip: false,
      customRender: ({ text }) => toDateString(text),
      ellipsis: true
    },
    {
      title: '时长',
      dataIndex: 'duration',
      width: 50
    },
    // {
    //   title: '文件大小',
    //   dataIndex: 'length',
    //   sorter: true,
    //   showSorterTooltip: false,
    //   ellipsis: true,
    //   width: 80
    // },
    // {
    //   title: '上传时间',
    //   dataIndex: 'createTime',
    //   sorter: true,
    //   showSorterTooltip: false,
    //   ellipsis: true,
    //   customRender: ({ text }) => toDateString(text),
    //   width: 160
    // },
    {
      title: '操作',
      key: 'action',
      width: 50,
      align: 'center'
    }
  ]);

  // 表格选中数据
  const selection = ref([]);

  // 表格数据源
  const datasource = ({ page, limit, where, orders }) => {
    console.log("Datasource called with:", { page, limit, where, orders });
    return pageFiles({ ...where, ...orders, page, limit });
  };

  /* 搜索 */
  const reload = (where) => {
    selection.value = [];
    console.log("reload======value==where ====>",where);
    tableRef?.value?.reload({ page: 1, where });
  };

  /* 打开播放弹窗 */
  const openPlay = (row) => {
    current.value = row ? { ...row } : null;
    if (current.value && current.value.fileRecords) {
      console.log('===openPlay===>',current.value.fileRecords);
      currentRecordList.value = current.value.fileRecords;
    } else {
      // 处理错误情况，比如设置一个空数组或显示错误消息
      currentRecordList.value = []; // 或者其他适当的默认值
      console.error("fileRecords is missing or current.value is null/undefined");
    }
    showPlay.value = true;
    console.log("openEdit======value===>",current.value, currentRecordList.value);
  };

  const groupMap = computed(() => {
    console.log('groupList:', props.groupList);
    const map = props.groupList.reduce((map, item) => {
      map[item.groupNo] = item.groupName;
      return map;
    }, {});
    console.log('groupMap:', map);
    return map;
  });

  /* 删除单个 */
  const remove = (row) => {
    const hide = messageLoading('请求中..', 0);
    removeFile(row.id)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的文件吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = messageLoading('请求中..', 0);
        removeFiles(selection.value.map((d) => d.id))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 上传 */
  const onUpload = ({ file }) => {
    if (file.size / 1024 / 1024 > 100) {
      message.error('大小不能超过 100MB');
      return false;
    }
    const hide = messageLoading({
      content: '上传中..',
      duration: 0,
      mask: true
    });
    uploadFile(file)
      .then(() => {
        hide();
        message.success('上传成功');
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
    return false;
  };

  defineExpose({ reload });
</script>

